﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;

namespace iwss.Document
{
    public static class TraceProvider
    {
        private static SPDiagnosticsCategory errorCategory = new SPDiagnosticsCategory("iwss", TraceSeverity.Monitorable, EventSeverity.Error);

        private static SPDiagnosticsCategory infoCategory = new SPDiagnosticsCategory("iwss", TraceSeverity.Verbose, EventSeverity.Information);
        
        public static void WriteLog(string msg)
        {
            WriteLog(msg, infoCategory);
        }

        public static void WriteLog(string msg, SPDiagnosticsCategory category)
        {
            SPDiagnosticsService diagSvc = SPDiagnosticsService.Local;
            diagSvc.WriteTrace(0, category, category.TraceSeverity, msg, null);
        }

        public static void LogError(string error)
        {
            WriteLog(error, errorCategory);
        }

        public static void LogError(Exception ex)
        {
            LogError(FormatException(ex));
        }

        public static void LogError(string error, Exception ex)
        {
            LogError(error);
            LogError(ex);
        }

        public static void LogInfo(string info)
        {
            WriteLog(info, infoCategory);
        }

        public static void LogInfo(Exception ex)
        {
            LogInfo(FormatException(ex));
        }

        public static void LogInfo(string info, Exception ex)
        {
            LogInfo(info);
            LogInfo(ex);
        }

        private static string FormatException(Exception ex)
        {
            StringBuilder stringBuilder = new StringBuilder();

            return AppendErrorString(stringBuilder, ex);
        }

        private static string AppendErrorString(StringBuilder stringBuilder, Exception ex)
        {
            stringBuilder.AppendLine(ex.ToString());

            if (ex.InnerException != null)
            {
                return AppendErrorString(stringBuilder, ex.InnerException);
            }
            else
            {
                return stringBuilder.ToString();
            }
        }
    }
}
